package cit.project.capeclear;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PaymentResult extends Activity {

	private Bundle b;
	private String paymentID = "";
	private String quantity = "";
	private String serviceName = "";
	private ArrayList<Item> v;

	final static String urlGoogleChart = "http://chart.apis.google.com/chart";
	final static String urlQRApi = "?chs=300x300&cht=qr&chl=";
	static String qrMessage = "";
	
	boolean anyTicketPrinted = false;
	int itemIndex = 0;
	int lastTicket = -1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.payment_result_layout);
	    
        b = getIntent().getExtras();
        paymentID = b.getString("paymentID");
        
        // Gets the array of Items from the previous activity
        v = getIntent().getExtras().getParcelableArrayList("items");
        lastTicket = lastTicketIndex();
        
        // Loads the first timen
        while(!loadItem(itemIndex) && itemIndex <= lastTicket)
        	itemIndex++;
        
        // Listener for the "Save ticket" button
        findViewById(R.id.buttonTicket).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				// Hides the button, so it is not saved
				v.setVisibility(View.INVISIBLE);
				
				// Saves the canvas to the galery
		        View resultLayout = findViewById(R.id.paymentResultLayout);
		        Bitmap image = Bitmap.createBitmap(resultLayout.getWidth(), resultLayout.getHeight(), Bitmap.Config.ARGB_8888);


		        findViewById(R.id.paymentResultLayout).draw(new Canvas(image));
		        String url = Images.Media.insertImage(getContentResolver(), image, "title", null);
		        Toast.makeText(PaymentResult.this,
				           "Ticket saved in gallery. " + url,
				           Toast.LENGTH_LONG).show();	
				
		        if(itemIndex < lastTicket)
		        	findViewById(R.id.buttonNextTicket).setVisibility(View.VISIBLE);
			}
		});
        

        findViewById(R.id.buttonNextTicket).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				v.setVisibility(View.GONE);
				findViewById(R.id.qrview).setVisibility(View.GONE);
				findViewById(R.id.qrProgressBar).setVisibility(View.VISIBLE);
				
				boolean ticketFound = false;
		        // Loads the next item
				itemIndex++;
		        while(!(ticketFound = loadItem(itemIndex)) && itemIndex <= lastTicket)
		        	itemIndex++;
		        
		        if(!ticketFound)
	        		findViewById(R.id.tvResultText).setVisibility(View.VISIBLE);
			}
		});
        	

        if (!anyTicketPrinted)
        {
        	findViewById(R.id.qrProgressBar).setVisibility(View.GONE);
        	findViewById(R.id.tvResultText).setVisibility(View.VISIBLE);
        }

	}

	void getQRCode ()
	{
		// Manages the QR code download in a background thread.
		Thread qrCodeThread = new Thread() {
			public void run() {

				Log.d("LG", "Running qrCodeThread");
		        final Bitmap bm = loadQRCode();
		        if(bm == null){
		         Toast.makeText(PaymentResult.this,
		           "Problem in loading QR Code1",
		           Toast.LENGTH_LONG).show();
		        }else
		        {
			        runOnUiThread( new Runnable()
			        {
			            @Override
			            public void run()
			            {
			            	findViewById(R.id.qrProgressBar).setVisibility(View.GONE);
			            	((ImageView) findViewById(R.id.qrview)).setImageBitmap(bm);
			            	findViewById(R.id.qrview).setVisibility(View.VISIBLE);
			            	findViewById(R.id.buttonTicket).setVisibility(View.VISIBLE);
			            }
			        } );
			        
		        
		        }
		     }
		};
		qrCodeThread.start();
	}

	
	
	//downloads the QR code
	private Bitmap loadQRCode(){
		Bitmap bmQR = null;
		InputStream inputStream = null;
	     
		Log.d("PR", "Loading QR: "+qrMessage);
		try {
			inputStream = OpenHttpConnection(urlGoogleChart + urlQRApi + qrMessage);
			bmQR = BitmapFactory.decodeStream(inputStream);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bmQR;
    }
	   
	   private InputStream OpenHttpConnection(String strURL) throws IOException{
	    InputStream is = null;
	    URL url = new URL(strURL);
	    URLConnection urlConnection = url.openConnection();
	     
	    try{
	     HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
	     httpConn.setRequestMethod("GET");
	     httpConn.connect();
	      
	     if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
	      is = httpConn.getInputStream(); 
	     }
	     }catch (Exception ex){
	     }
	     
	    return is; 
	   }
	   
	   
	   // Returns true if the phone is online
		boolean isOnline() {
			ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getActiveNetworkInfo();

			if (netInfo != null && netInfo.isConnectedOrConnecting()) 
				return true;

			else
				return false;
		}

		int lastTicketIndex ()
		{
			int last = -1;
			for (int i=0; i<v.size(); i++ )
				if(v.get(i).shipment == 0)
					last = i;
			
			return last;
		}
		
		//Loads the item
		boolean loadItem (int itemNumber)
		{
			boolean ticketFound = false;
			
			if (itemNumber < v.size())
				if (v.get(itemNumber).shipment == 0)
				{
					ticketFound = true;
					anyTicketPrinted = true;
					
					Item it = v.get(itemNumber);
					serviceName = it.shopName;
					quantity = (it.quantity)+" ";
					
			        qrMessage = URLEncoder.encode("Ticket for "+ serviceName +
			        		". Quantity: "+ quantity + ". ID: " + paymentID);
			        
			        ((TextView)findViewById(R.id.tvPaymentResult)).setText(serviceName);
	
					if (isOnline())
						getQRCode();
					else
					{
						findViewById(R.id.qrProgressBar).setVisibility(View.GONE);
						findViewById(R.id.tvNoNetwork).setVisibility(View.VISIBLE);
					}
	
				}
			return ticketFound;
		}
	   
}
